/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 * <p>
 * https://www.renren.io
 * <p>
 * 版权所有，侵权必究！
 */

package com.theme.passport.controller.app;

import com.theme.common.base.JSONHandler;
import com.theme.common.base.StringHandler;
import com.theme.common.frame.exception.ErrorCode;
import com.theme.common.mvc.utils.RedisKeys;
import com.theme.common.mvc.validator.ValidatorUtils;
import com.theme.common.mvc.view.R;
import com.theme.common.third.apple.bean.CusJws;
import com.theme.common.third.apple.bean.JwsPayload;
import com.theme.passport.annotation.Login;
import com.theme.passport.controller.app.utils.AppContextUtil;
import com.theme.passport.entity.ThirdUserEntity;
import com.theme.passport.entity.UserEntity;
import com.theme.passport.entity.constant.UserOriginEnum;
import com.theme.passport.form.AccountBindMobileForm;
import com.theme.passport.form.AppleLoginForm;
import com.theme.passport.service.AppleLoginService;
import com.theme.passport.service.ThirdUserService;
import com.theme.passport.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Date;

/**
 * 账号绑定
 * 1、Apple账号绑定手机号
 * 2、手机号绑定Apple账号
 * 3、账号合并 ？
 * @author Mark sunlightcs@gmail.com
 */
@RestController
@RequestMapping("/app/account")
@Api("APP账号绑定解绑[密码登录，手机验证码登录，微信登录，QQ登录]")
public class AccountBindController {

    private static final Logger logger = LoggerFactory.getLogger(AccountBindController.class);

    @Autowired
    private UserService userService;
    @Autowired
    private ThirdUserService thirdUserService;
    @Autowired
    private AppleLoginService appleLoginService;

    @Resource(name = "redisTemplate")
    private ValueOperations<String, String> redisCache;

    @Value("${user.default-avatar}")
    private String defaultAvatar ;

    @Login
    @PostMapping("bindMobile")
    @ApiOperation("Apple登录情况下绑定手机号")
    public R bindMobile(@RequestBody AccountBindMobileForm form) {

        //表单校验
        ValidatorUtils.validateEntity(form);

        //校验验证码是否合适
        R r = validatorCode(form.getMobile(),form.getCode());
        if (!R.isOk(r)){
            return r;
        }

        //判断该账号是否已被注册或者绑定
        UserEntity userEntity = userService.queryByMobile(form.getMobile());
        if (userEntity != null){
            return R.error(ErrorCode.BIND_MOBILE_BIND_APPLE_EXIST.getCode(),ErrorCode.BIND_MOBILE_BIND_APPLE_EXIST.getMsg());
        }

        UserEntity currentUser = AppContextUtil.getCurrentUser();
        UserEntity user = userService.getById(currentUser.getId());
        user.setMobile(form.getMobile());
        user.setUpdateTime(new Date());

        userService.updateUserById(user);

        return R.ok();
    }

    @Login
    @PostMapping("bindApple")
    @ApiOperation("手机号登录情况下绑定Apple")
    public R bindApple(@Valid AppleLoginForm form) {
        // 查询用户是否已经绑定了手机号
        UserEntity currentUser = AppContextUtil.getCurrentUser();
        ThirdUserEntity thirdUser = thirdUserService.queryByUserId(currentUser.getId());
        if (thirdUser != null){
            return R.error(ErrorCode.BIND_APPLE_BIND_MOBILE_USER_EXIST.getCode(),ErrorCode.BIND_APPLE_BIND_MOBILE_USER_EXIST.getMsg());
        }

        logger.info("苹果账号应用授权登录,参数为：{}", JSONHandler.getGson().toJson(form));
        R valid = appleLoginService.appLoginHandler(form.getIdentityToken());
        logger.info("苹果登陆授权 idToken 验证结果：{}" , JSONHandler.objectToJson(valid));
        if (!R.isOk(valid)){
            logger.info("苹果登陆授权 idToken 验证失败!");
            return valid;
        }
        String cusJwsStr = valid.get("cusJws").toString();
        CusJws cusJws = JSONHandler.getGson().fromJson(cusJwsStr, CusJws.class);
        JwsPayload jwsPayload = cusJws.getJwsPayload();
        logger.info("根据identityToken解析苹果用户信息：jwsPayload：{}", JSONHandler.getGson().toJson(cusJws.getJwsHeader()));
        ThirdUserEntity thirdUserEntity = thirdUserService.queryByOpenid(UserOriginEnum.APPLE.getValue(), jwsPayload.getSub());
        if (thirdUserEntity != null){
            // 查询该账号下是否存在手机号
            UserEntity user = userService.getById(thirdUserEntity.getUserId());
            if (user != null && user.getMobile() != null){
                return R.error(ErrorCode.BIND_MOBILE_BIND_APPLE_EXIST.getCode(),ErrorCode.BIND_MOBILE_BIND_APPLE_EXIST.getMsg());
            }
            // 账号合并 1、修改绑定关系 2、删除之前只用Apple登录的账号，以手机号账号为主
            thirdUserEntity.setUserId(currentUser.getId());
            thirdUserEntity.setNickname(form.getNickname());
            thirdUserService.updateById(thirdUserEntity);
            userService.removeById(thirdUserEntity.getUserId());
            return R.ok();
        }
        //注册thrid账号跟用户绑定
        thirdUserEntity = new ThirdUserEntity();
        thirdUserEntity.setUserId(currentUser.getId());
        thirdUserEntity.setOpenid(jwsPayload.getSub());
        thirdUserEntity.setAvatar(defaultAvatar);
        thirdUserEntity.setCountry("-");
        thirdUserEntity.setProvince("-");
        thirdUserEntity.setCity("-");
        thirdUserEntity.setGender(0);
        thirdUserEntity.setStatus(1);
        thirdUserEntity.setNickname(form.getNickname());
        thirdUserEntity.setOrigin(UserOriginEnum.APPLE.getValue());
        thirdUserEntity.setCreateTime(new Date());
        thirdUserEntity.setUpdateTime(new Date());
        thirdUserService.insert(thirdUserEntity);
        return R.ok();
    }


    @Login
    @PostMapping("unBindApple")
    @ApiOperation("手机号登录情况下解除绑定Apple账号")
    public R unBindApple() {
        // 查询用户是否已经绑定了
        UserEntity currentUser = AppContextUtil.getCurrentUser();
        ThirdUserEntity thirdUser = thirdUserService.queryByUserId(currentUser.getId());
        if (thirdUser == null){
            return R.ok();
        }
        thirdUserService.deleteById(thirdUser.getId());
        return R.ok();
    }

    private R validatorCode(String mobile, String code) {
        String loginKey = RedisKeys.SEND_CODE.concat(mobile);
        String result = redisCache.get(loginKey);
        if (StringHandler.isEmpty(result)){
            return R.error(ErrorCode.FORM_USER_CODE_ERROR.getCode(),"验证码已过期");
        }
        if (result.equals(code)){
            return R.ok();
        }
        return R.error(ErrorCode.FORM_USER_CODE_ERROR.getCode(),ErrorCode.FORM_USER_CODE_ERROR.getMsg());
    }

}
